<script setup lang="ts">
import {inject, onMounted, ref, watch} from 'vue'
import {BACKEND_URL} from "../request/Api.ts";
import {useCartStore} from "../stores/cart.ts";
import router from "../router";
import {ElNotification} from "element-plus";
import {ShoppingCart} from '@element-plus/icons-vue'
import {formatPrice} from "../util/formatPrice.ts";

const cart = useCartStore()
// 轮播图数据
const carouselItems = ref([
  {
    id: 0,
    image: '',
    PicUrl: '',
    Type: ''
  },
])

// 热门茶叶数据
const hotTeas = ref([
  {
    id: 0,
    image: '',
    name: '',
    rating: 0,
    reviews: 2,
    Pirce: 0,
    tag: '新品',
    tagColor: 'red',
    promotion: {
      freeShipping: true,
      cashback: 5
    }
  },
])

// 添加到购物车
const addToCart = (tea: any) => {
  cart.add({
    id: tea.id,
    title: tea.name,
    image: tea.image,
    price: tea.Pirce,
    qty: 1,
  })
  ElNotification({
    title: `商品:${tea.name}添加成功`,
    type: 'success',
    showClose: false,
    position: 'bottom-right'
  })
}

// 推薦商品（左侧大图）
const featuredProduct = ref({
  id: '',
  image: '',
  name: '',
  description: '精选明前龙井，香气清高，滋味鲜爽，是春季不可错过的佳品。',
  price: 299,
  oldPrice: 399
})

// 推薦商品列表
const recommendedProducts = ref([
  {id: 101, image: '', name: '', price: 0, oldPrice: 0},
])

//跳转详情页
const goDetail = (id: any) => {
  router.push(`/detail/${id}`)
}

//打开网站
const openSite = (PicUrl: string) => {
  window.open(PicUrl)
}
/**
 * 获取首页数据
 *从Layout中注入数据
 */
const mainData: any = inject('main')
const processData = () => {
  if (mainData.value) {
    const res = mainData.value;

    // 轮播图
    carouselItems.value = res.SlidesList.map((item: any) => ({
      id: item.Id,
      image: BACKEND_URL + '/images/Slides/' + item.PicName,
      PicUrl: item.PicUrl,
      Type: item.Type
    }))

    // 热门数据
    if (res.GoodsList && Array.isArray(res.GoodsList)) {
      hotTeas.value = res.GoodsList.map((item: any) => ({
        id: item.Id,
        image: BACKEND_URL + '/images/UpLoadPic/' + item.PicUrls,
        name: item.GoodsName,
        Pirce: item.Pirce,
        reviews: item.Views,
        rating: item.StarCount / 2,
        tag: '新品',
        tagColor: 'red'
      }))
    }

    // 推荐数据(大图)
    if (res.HotGoods) {
      featuredProduct.value = {
        id: res.HotGoods.Id,
        image: BACKEND_URL + '/images/UpLoadPic/' + res.HotGoods.PicUrls,
        name: res.HotGoods.GoodsName,
        description: '精选推荐商品',
        price: res.HotGoods.Pirce,
        oldPrice: res.HotGoods.Pirce * 1.2
      }
    }

    // 推荐数据(小图)
    if (res.GoodsList && Array.isArray(res.GoodsList)) {
      recommendedProducts.value = res.GoodsList.map((item: any) => ({
        id: item.Id,
        image: BACKEND_URL + '/images/UpLoadPic/' + item.PicUrls,
        name: item.GoodsName,
        price: item.Pirce,
      }))
    }
  }
}

//监听数据变化
if (mainData) {
  watch(mainData, () => {
    processData();
  }, {immediate: true})
}


//钩子函数
onMounted(() => {
})
</script>

<template>
  <div class="home">
    <div class="carousel-section">
      <div class="right-carousel">
        <el-carousel
            :interval="4000"
            arrow="hover"
            height="480px"
            class="carousel"
        >
          <el-carousel-item
              v-for="item in carouselItems.filter(item => item.Type === 'D')"
              :key="item.id"
              @click="openSite(item.PicUrl)"
          >
            <img :src="item.image" alt="" class="carousel-image">
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>

    <div class="content">
      <div class="section-title">
        <span>熱門商品</span>
      </div>

      <!-- 热门茶叶网格 -->
      <div class="tea-grid">
        <div
            v-for="tea in hotTeas"
            :key="tea.id"
            class="tea-card"

        >
          <div class="tea-image" @click="goDetail(tea.id)">
            <img :src="tea.image" :alt="tea.name">
          </div>

          <div class="tea-info">
            <div class="tea-name">
              <el-tooltip :content="tea.name" placement="top">
                <div class="tea-name-text">{{ tea.name }}</div>
              </el-tooltip>
            </div>

            <div class="tea-rating" @click="goDetail(tea.id)">
              <el-rate
                  v-model="tea.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
              />
              <span class="reviews">({{ tea.reviews }})</span>
            </div>

            <div class="tea-actions">
              <div class="tea-row">
                <span class="tea-price-symbol">
                  HK$
                </span>
                <div class="tea-price">
                  <span>
                  {{ formatPrice(tea.Pirce) }}
                  </span>
                  <span>
                    元
                  </span>
                </div>
              </div>

              <el-button
                  type="primary"
                  class="add-to-cart-btn"
                  @click="addToCart(tea)"
              >
                加入購物車
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 推薦商品 -->
      <div class="section-title-left">
        <span >推薦商品</span>
      </div>

      <div class="recommend-grid">
        <!-- 左侧大图 -->
        <div class="featured-card">
          <span @click="goDetail(featuredProduct.id)">
          <img :src="featuredProduct.image" :alt="featuredProduct.name" class="featured-image"/>
          </span>
          <div class="featured-info">
            <div class="featured-name">
              <el-tooltip :content="featuredProduct.name" placement="top">
                <div class="featured-name-text">{{ featuredProduct.name }}</div>
              </el-tooltip>
            </div>
            <div class="featured-desc">{{ featuredProduct.description }}</div>
            <div class="featured-pricing">
              <span class="featured-price">HK${{formatPrice(featuredProduct.price) }}</span>
              <el-button type='primary' class="buy-btn" @click="addToCart(featuredProduct)">立即購買</el-button>
            </div>
          </div>
        </div>

        <!-- 右侧列卡片 -->
        <div class="side-grid">
          <div class="small-card" v-for="p in recommendedProducts" :key="p.id">
            <span @click="goDetail(p.id)">
              <img :src="p.image" :alt="p.name" class="small-image"/>
            </span>
            <div class="small-info">
              <div class="small-name" @click="goDetail(p.id)">
                <el-tooltip :content="p.name" placement="top">
                  <div class="small-name-text">{{ p.name }}</div>
                </el-tooltip>
              </div>
              <div class="small-pricing">
                <div class="small-price-container">
                  <span class="small-price-symbol">HK$</span>
                  <span class="small-price">{{formatPrice(p.price)}}</span>
                  <span class="small-price">元</span>
                </div>
                <el-button class="small-add-btn" type="primary" size="small" :icon="ShoppingCart" solid
                           @click="addToCart(p)"/>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<style scoped>
.home {
  border-radius: 18px;
  overflow: hidden;
  max-width: 1400px;
  margin: 0 auto;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.small-price-container {
  display: flex;
}

.small-price-symbol {
  margin-right: 5px;
  font-weight: bold;
  color: white;
}

.tea-row {
  display: flex;
}

.tea-price-symbol {
  color: white;
  font-weight: bold;
}

.carousel {
  border-radius: 15px;
  overflow: hidden;
}

.carousel-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}


.right-carousel {
  margin: 0 20px;
  flex: 2;
  width: 66.667%;
  border-radius: 15px;
  overflow: hidden;
}

.content {
  padding: 20px;
}

.section-title {
  text-align: center;
  margin: 30px 0;
}

.tea-actions {
  display: flex;
}

.section-title span {
  font-size: 45px;
  font-weight: bold;
  color: rgba(235, 235, 235, 0.79);
}

/* 茶叶网格布局 */
.tea-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.tea-card {
  border-radius: 12px;
  background-color: #2c3e50;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.tea-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.tea-image {
  position: relative;
  height: 250px;
  overflow: hidden;
}

.tea-image img {
  width: 100%;
  height: 100%;
}

.tea-info {
  padding: 15px;
}

.tea-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.tea-name-text {
  overflow: hidden;
  color: white;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tea-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.reviews {
  margin-left: 8px;
  color: #666;
  font-size: 14px;
}

.tea-price {
  font-size: 18px;
  font-weight: bold;
  color: #666;
  display: flex;
  margin: 0 10px;
}

.add-to-cart-btn {
  width: 100%;
  border-radius: 6px;
}

/* 推薦商品 */
.section-title-left {
  text-align: left;
  margin: 36px 0 20px;
}

.section-title-left span {
  font-size: 32px;
  margin: 0 20px;
  font-weight: 800;
  color: #bdbdbd;
}

.recommend-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  align-items: start;
}

.featured-card {
  background-color: #2c3e50;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  height: 100%;
  flex-direction: column;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.featured-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.featured-image {
  width: 100%;
  height: 290px;
  object-fit: cover;
}

.featured-info {
  padding: 10px;
}

.featured-name {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin-bottom: 10px;
}

.featured-name-text {
  overflow: hidden;
  color: white;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.featured-desc {
  color: #666;
  line-height: 1.6;
  margin-bottom: 12px;
}

.featured-pricing {
  display: flex;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 16px;
}

.featured-price {
  color: white;
  font-size: 22px;
  font-weight: 800;
}

.buy-btn {
  width: 120px;
}

.side-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.small-card {
  background-color: #2c3e50;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.small-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.small-image {
  width: 100%;
  height: 140px;
}

.small-info {
  padding: 12px;
}

.small-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 6px;
}

.small-name-text {
  overflow: hidden;
  color: white;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.small-pricing {
  justify-content: space-between;
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.small-price {
  color: rgba(255, 255, 255, 0.67);
  font-weight: 700;
  margin: 0 5px;
}

@media (max-width: 768px) {
  .carousel-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .carousel-section {
    flex-direction: column;
    gap: 10px;
  }

  .right-carousel {
    margin: 0 10px;
    border-radius: 0;
    width: 100%;
  }

  .carousel {
    height: 300px !important;
  }

  .tea-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
  }

  .content {
    padding: 15px;
  }

  .recommend-grid {
    grid-template-columns: 1fr;
  }

  .featured-image {
    height: 220px;
  }

  .small-add-btn {
    display: none;
  }
}

@media (max-width: 480px) {
  .carousel {
    height: 250px !important;
  }

  .right-carousel {
    margin: 0 5px;
  }

  .tea-grid {
    grid-template-columns: 1fr;
  }
}
</style>
